package com.ruiben.mall.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruiben.mall.LoginRequired;
import com.ruiben.mall.impl.*;
import com.ruiben.mall.pojo.*;
import com.ruiben.mall.utils.CommonJSONResult;
import com.ruiben.mall.utils.ImageUtils;
import com.ruiben.mall.utils.PagedResult;
import com.ruiben.mall.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ruiben.mall.config.ErrorConfig.*;

@RestController
@RequestMapping("order")
public class OrderListController extends BaseController {


    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private OrderBackServiceImpl orderback;

    @Autowired
    private UserOrderProductServiceImpl userOrderProductService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private CartServiceImpl cartService;


    /**
     * 返回 用户订单
     *
     * @return
     */
    @LoginRequired
    @PostMapping("getOrderListByUserId")
    public CommonJSONResult getOrderList(String userId, Integer page) {

        if (StringUtils.isBlank(userId)) {
            return CommonJSONResult.build(ID_NOT_EMPTY_CODE, ID_NOT_EMPTY_MSG, null);
        }

        if (page == null) {
            page = 1;
        }

        PagedResult orderList = orderService.getOrderList(userId, page, PAGE_SIZE);
        return CommonJSONResult.ok(orderList);
    }


    /**
     * @param userId 用户id
     * @return
     */
    @PostMapping("addOrder")
    @LoginRequired
    public CommonJSONResult addOrder(String userId, String[] cartIds, String addressId, BigDecimal total) {

//        if (StringUtils.isBlank(cartIdsStr)){
//            return CommonJSONResult.errorMsg("购物车id不能为空");
//        }
//
//        String[] cartIds = cartIdsStr.split(",");

        if (cartIds == null || cartIds.length <= 0) {
            return CommonJSONResult.errorMsg("购物车id不能为空");
        }


        if (StringUtils.isBlank(userId)) {
            return CommonJSONResult.build(USER_ID_NOT_EMPTY_CODE, USER_ID_NOT_EMPTY_MSG, null);
        }

        if (total == null) {
            return CommonJSONResult.errorMsg("合计金额不能为空");
        }

        BigDecimal totalRes = new BigDecimal(0);
        for (String cartId : cartIds) {
            UserCart cartInfo = cartService.getCartInfo(cartId);

            totalRes = totalRes.add(new BigDecimal(cartInfo.getProductPrice() * cartInfo.getProductnum()));
        }

        if (total.compareTo(totalRes) != 0) {
            return CommonJSONResult.errorMsg("价格不相符");
        }

//        //获取用户余额，是否有足够的钱来支付
//        UserVo userInfo = userService.getUserInfo(userId);
//        if (new BigDecimal(userInfo.getUserMoney()).compareTo(total) < 0){
//            return CommonJSONResult.errorMsg("对不起，余额不足，请充值");
//        }


        UserOrder userOrder = orderService.addOrder(userId, cartIds, addressId);

        if (userOrder != null) {

            return CommonJSONResult.ok(userOrder);
        }
        return CommonJSONResult.errorMsg("添加定单失败");
    }


    @PostMapping("confirmOrder")
    public CommonJSONResult confirmOrder(String userAddressId, String orderId, Integer payType, String orderContent) {

        if (StringUtils.isBlank(orderId)) {
            return CommonJSONResult.errorMsg("订单id不能为空");
        }

        if (payType == null) {
            return CommonJSONResult.errorMsg("支付方式不能为空");
        }


        if (StringUtils.isBlank(userAddressId)) {
            return CommonJSONResult.build(DELIVERY_ADDRESS_NOT_EMPTY_CODE, DELIVERY_ADDRESS_NOT_EMPTY_MSG, null);
        }


        boolean b = orderService.confirmOrder(userAddressId, orderId, payType, orderContent);

        if (b) {

            return CommonJSONResult.ok();
        }
        return CommonJSONResult.errorMsg("添加定单失败");
    }

    /**
     * 根据 id获取订单详情
     *
     * @param id
     * @return
     */
    @PostMapping("getOrderDetail")
    public CommonJSONResult getOrderDetailById(String id, Integer status) {

        if (StringUtils.isBlank(id)) {
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }

        if (status == null) {
            return CommonJSONResult.errorMsg("订单状态不能为空");
        }

        UserOrder orderDetail = orderService.getOrderDetailById(id, status);
        if (orderDetail != null) {

            return CommonJSONResult.ok(orderDetail);
        } else {
            return CommonJSONResult.errorMsg("没有查到相关订单");
        }
    }

    /**
     * 更新订单中的商品
     *
     * @return
     */
    @PostMapping("updateOrderProduct")
    public CommonJSONResult updateOrderProduct(String orderId, String product) {

        if (StringUtils.isBlank(orderId)) {
            return CommonJSONResult.errorMsg("订单id不能为空");
        }

        if (StringUtils.isBlank(product)) {
            return CommonJSONResult.errorMsg("更新的商品信息不能为空");
        }

        try {
            JSONObject json = JSON.parseObject(product);
            JSONArray jsonArray = json.getJSONArray("products");

            BigDecimal totalDecimal = new BigDecimal(0);
            List<UserOrderProduct> products = new ArrayList<>();
            for (Object aJsonArray : jsonArray) {
                JSONObject jsonObject = (JSONObject) aJsonArray;
                String goodid = jsonObject.getString("id");
                int num = jsonObject.getInteger("productNum");
                BigDecimal price = jsonObject.getBigDecimal("productPrice");
                totalDecimal = totalDecimal.add(price.multiply(new BigDecimal(num)));
                UserOrderProduct userOrderProduct = new UserOrderProduct();
                userOrderProduct.setProductnum(num);
                userOrderProduct.setProductprice(price);
                userOrderProduct.setId(goodid);
                products.add(userOrderProduct);

            }

            boolean b = orderService.updateOrderProduct(orderId, products, totalDecimal);

            if (b) {
                return CommonJSONResult.ok();
            }
        } catch (Exception e) {
            return CommonJSONResult.errorMsg("更新失败");
        }

        return CommonJSONResult.errorMsg("更新失败");

    }

    /**
     * 退换货
     *
     * @return
     */
    @PostMapping("returnGoods")
    public CommonJSONResult returnGoods(String userId,
                                        String orderId,
                                        Integer type,
                                        String backContent,
                                        String goodsId,
                                        String[] photos) {

        if (StringUtils.isBlank(userId)) {
            return CommonJSONResult.errorMsg("用户id不能为空");
        }

        if (StringUtils.isBlank(orderId)) {
            return CommonJSONResult.errorMsg("定单id不能为空");
        }

        if (type == null) {
            return CommonJSONResult.errorMsg("退货类型不能为空");
        }

        if (StringUtils.isBlank(backContent)) {
            return CommonJSONResult.errorMsg("问题描述不能为空");
        }
//
//        if (photos == null || photos.length <= 0){
//            return CommonJSONResult.errorMsg("图片不能为空");
//        }

        UserOrderBack userOrderBack = new UserOrderBack();
        userOrderBack.setUserid(userId);
        userOrderBack.setOrderid(orderId);
        userOrderBack.setType((short) (type.intValue()));
        userOrderBack.setBackcontent(backContent);
        userOrderBack.setOrderbacktime(new Date());
        userOrderBack.setOrderbackstatus(false);


        if (photos != null && photos.length > 0) {
            if (photos.length == 1) {
                userOrderBack.setBackphoto1(ImageUtils.replaceImg(photos[0]));
            }
            if (photos.length == 2) {
                userOrderBack.setBackphoto1(ImageUtils.replaceImg(photos[0]));
                userOrderBack.setBackphoto1(ImageUtils.replaceImg(photos[1]));
            }
            if (photos.length == 3) {
                userOrderBack.setBackphoto1(ImageUtils.replaceImg(photos[0]));
                userOrderBack.setBackphoto1(ImageUtils.replaceImg(photos[1]));
                userOrderBack.setBackphoto1(ImageUtils.replaceImg(photos[2]));
            }
        }


        boolean b = orderService.returnGoods(userOrderBack, goodsId);
        if (b) {
            return CommonJSONResult.ok();
        }
        return CommonJSONResult.errorMsg("退货失败");
    }


    /**
     * 获取售后列表
     *
     * @param page
     * @param orderBackStatus
     * @return
     */
    @PostMapping("getUserOrderBackList")
    public CommonJSONResult getUserOrderBackList(Integer page, Integer orderBackStatus) {

        if (page == null) {
            page = 1;
        }

        PagedResult userOrderBackList = orderService.getUserOrderBackList(page, PAGE_SIZE, orderBackStatus);

        return CommonJSONResult.ok(userOrderBackList);
    }


    /**
     * 根据id获取订单售后详情
     *
     * @param id
     * @return
     */
    @PostMapping("getOrderBackDetail")
    public CommonJSONResult getUserOrderBackDetailById(String id) {
        if (StringUtils.isBlank(id)) {
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }

        UserOrderBack userOrderBackDetail = orderService.getUserOrderBackDetailById(id);
        if (userOrderBackDetail != null) {
            return CommonJSONResult.ok(userOrderBackDetail);
        }

        return CommonJSONResult.errorMsg("没有查询到该售后商品");

    }


    /**
     * 完成订单
     *
     * @param id
     * @return
     */
    @PostMapping("finishOrderBack")
    public CommonJSONResult finishOrderBack(String id) {
        UserOrderBack userOrderBack = new UserOrderBack();
        userOrderBack.setId(id);
        userOrderBack.setOrderbackstatus(true);

        boolean b = orderService.finishOrderBack(userOrderBack);

        if (b) {
            return CommonJSONResult.ok();
        }

        return CommonJSONResult.errorMsg("确认失败");
    }


    @LoginRequired
    @PostMapping("getOrderListForStatus")
    public CommonJSONResult getOrderListForStatus(String userId, Integer status, Integer page) {
        if (status == null) {
            status = 1;
        }

        if (page == null) {
            page = 1;
        }
        PagedResult orderListForStatus = orderService.getOrderListForStatus(userId, status, page, PAGE_SIZE);
        return CommonJSONResult.ok(orderListForStatus);
    }

    @LoginRequired
    @PostMapping("confirmGoods")
    public CommonJSONResult confirmGoods(String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }

        UserOrder userOrder = new UserOrder();
        userOrder.setId(orderId);
        userOrder.setOrderstatus((short) 4);

        boolean b = orderService.updateOrder(userOrder);
        if (b) {
            return CommonJSONResult.ok();
        }

        return CommonJSONResult.errorMsg("确认收货失败");
    }

    @PostMapping("delOrder")
    public CommonJSONResult delOrder(String id) {
        if (StringUtils.isBlank(id)) {
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }

        boolean b = orderService.delOrder(id);
        if (b) {
            return CommonJSONResult.ok();
        }
        return CommonJSONResult.errorMsg("删除失败");
    }

    @PostMapping("cancelOrder")
    public CommonJSONResult cancelOrder(String id) {
        if (StringUtils.isBlank(id)) {
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }

        UserOrder userOrder = new UserOrder();
        userOrder.setOrderstatus((short) 7);
        userOrder.setId(id);

        boolean b = orderService.updateOrder(userOrder);
        if (b) {
            return CommonJSONResult.ok();
        }
        return CommonJSONResult.errorMsg("删除失败");
    }


    /**
     * 获取退货单详情
     */
    @PostMapping("getOrderBackList")
    public CommonJSONResult getOrderBackList(String userId) {


        if (StringUtils.isBlank(userId)) {
            return CommonJSONResult.errorMsg("用户id不能为空");
        }

        List<UserOrderBack> orderBackDetail = orderback.getOrderBackDetail(userId);
        return CommonJSONResult.ok(orderBackDetail);
    }

    @LoginRequired
    @PostMapping("getGoodsListForOrderId")
    public CommonJSONResult getGoodsListForOrderId(String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }

        UserOrder orderById = orderService.getOrderById(orderId);
        String id = orderById.getId();
        List<UserOrderProduct> goodslistForOrderId = userOrderProductService.getGoodslistForOrderId(id);
        return CommonJSONResult.ok(goodslistForOrderId);
    }


    @PostMapping("getCommentGoodsList")
    @LoginRequired
    public CommonJSONResult getCommentGoodsList(String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return CommonJSONResult.errorMsg(ID_NOT_EMPTY_MSG);
        }

        UserOrder commentGoodsList = orderService.getCommentGoodsList(orderId);
        if (commentGoodsList != null) {

            return CommonJSONResult.ok(commentGoodsList);
        } else {
            return CommonJSONResult.errorMsg("没有相关数据");
        }
    }

}
